<!-- eslint-disable vue/no-parsing-error -->
<!-- eslint-disable vue/valid-v-bind -->
<template>
  <div>
    <div v-if="searchForm" style=" background-color: #fff; border-radius:10px;">
      <search-form :search-form="searchForm" :model-type="modelType" :button-group="buttonGroup"
        @searchFormEmit="searchFormEmit" @refreshForm="refreshForm" @watchTypeEmit="watchTypeEmit" />
    </div>
    <div style="border-radius: 10px; background-color: #fff; margin-bottom: 16px">
      <el-table v-if="showTable" ref="multipleTableRef" v-loading="loading" :data="tableData" :height="height"
        :row-class-name="rowClassName" :header-cell-style="headerCellStyle" :cell-style="tableCellStyle"
        style="width: 100%; border-radius: 10px; margin-bottom: 16px;" border @selection-change="handleSelectionChange"  @select-all="handleSelectAll"
        :span-method="arraySpanMethod">
        <!-- :span-method="({ row, column, rowIndex, columnIndex })=>{ return this.rowSpan(row, column, rowIndex, columnIndex,1,'ZzType')}" -->
        <!-- @sort-change="sortChange" -->
        <el-table-column v-if="multipleTable === true" type="selection" width="55" />
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in tableTitle.filter(item2 => item2.show)" :key="index" 
          :prop="item.value"
          :label="item.label" 
          :width="item.width" 
          :sortable="item.sortable === true"
          :align="item.align ? item.align : 'center'" 
          :render-header="renderHeader"
          >
          <!-- :render-header="renderHeader" -->
          <template v-slot="scope">
            <template v-if="item.type === 'text'">
              {{ scope.row[item.value] }}
            </template>
            <template v-else-if="item.type === 'slot'">
              <slot :name="item.slot" :row="scope.row" :column="item.prop" :index="scope.$index" />
            </template>
            <template v-else-if="item.type === 'router'">
              <router-link
                :to="{ path: item.path, query: Object.assign({}, item.query, getQuery(item.params, scope.row)) }"
                style="color: #409EFF">
                {{ scope.row[item.value] }}
              </router-link>
            </template>
            <template v-else-if="item.type === 'options'">
              <el-button v-for="(btn, btnKey) in item.options"
                v-show="scope.row.role && (scope.row.role[0].roleId === 0 && btn.au) ? false : true" :key="btnKey"
                :type="btn.type && btn.type !== '' ? btn.type : 'primary'" :icon="btn.icon ? btn.icon : ''" size="mini"
                @click="btn.clickEvent(scope.row)">
                {{ btn.text }}
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: flex-end;">
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize"
          @pagination="getPageList('next')" />
        <!-- 分页在这 -->
      </div>
    </div>
  </div>
</template>
<script>
import SearchForm from '@/components/SearchForm/index.vue'
import Pagination from '@/components/BasicTable/Pagination'
export default {
  name: 'BasicTable',
  components: { SearchForm, Pagination },
  props: {
    spanFunc: { type: Function, default: null },
    spanArr: { type: Array, default: Array },
    // 基本
    tableTitle: { type: Array, default: Array },
    dataSource: { type: Function, default: () => { } },
    dataParams: { type: Object, default: () => { } },
    maxPage: { type: Number, default: 50 },
    multipleTable: { type: Boolean, default: true },
    pagination: { type: Boolean, default: true },
    showTable: { type: Boolean, default: true },
    height: { type: Number, default: null },
    width: { type: Number, default: null },

    // eslint-disable-next-line vue/require-valid-default-prop
    headerCellStyle: {
      type: Object, default: function () {
        return { background: '#FAFBFD', color: '#6D6D6D', textAlign: 'center', }
      }
    },
    tableCellStyle: {
      type: Object, default: function () {
        return {}
      }
    },
    // 特别操作
    searchForm: { type: Object, default: null },
    isShowGroup: { type: Boolean, default: true },
    buttonGroup: { type: Object, default: null },
    leftButtonGroup: { type: Boolean, default: true },
    rightButtonGroup: { type: Boolean, default: true },
    modelType: { type: String, default: null },
    stripe: { type: Boolean, default: false },
    reload: { type: Boolean, default: false }
  },
  data() {
    return {
      loading: false,
      tableData: null,
      total: 0, // 分页的总数，但是如果数量大于500，就最多可以看500条数据，页码控制到50页以内可以点击分页
      listQuery: {
        page: 1,
        pageSize: 10
      },
      selectedRows: [], // 存储选中的行数据
      headerCheckbox: false
    }
  },
  watch: {
    dataParams(newVal) {
      this.updateListQuery(newVal)
    },
    // 重载
    reload(newVal) {
      if (newVal) {
        this.getPageList()
      }
    },
    listQuery(newVal) {
      this.getPageList()
      this.$emit('closeReload', false)
    }
  },
  computed: {
    // 判断是否全选
    isAllSelected() {
      return this.selectedRows.length === this.tableData.length && this.tableData.length > 0;
    }},
  created() {
    if (this.dataParams !== undefined) {
      this.updateListQuery(this.dataParams)
    }

  },

  methods: {
    // 处理身份证上面头部需要的复选框，拿到全选数据和样式
    renderHeader(h, { column }) {
    if(this.modelType === 'engineer' || this.modelType === 'contact' ){
        if (column.property === 'PerCard') {
          return h('div', { 
            style: { 
              
             } }, 
            [
        // 原始列标题文本
        h('span', column.label),
        // 右侧图标容器
          h('i', {
            class: {
              'el-icon-view': true,
              'active-icon': this.headerCheckbox, // 自定义激活状态类
            },
            style: { 
              'margin':'0 0 0 6px',
              'cursor': !this.headerCheckbox ?'pointer':'',
               'color': !this.headerCheckbox ? '#409EFF' : '#C0C4CC',
               'pointer-events': !this.headerCheckbox ?'':'none'
            },
            on: {
              click: (event) => {
                event.stopPropagation();
                 // // 切换选中状态
                const newVal = !this.headerCheckbox;
                this.headerCheckbox = newVal;
              if (newVal) {
                this.selectedRows = [...this.tableData];
            }
               this.$refs.multipleTableRef.toggleAllSelection(newVal);
        
              }
            }
          })
        
      ]);
      // 下面是复选框的样式，需要可以更改
      // return h('div', [
      //   h('el-checkbox', {
      //     props: { // 属性
      //       value: this.headerCheckbox,
      //       disabled: this.headerCheckbox // 选中状态时禁用
      //     },
      //     on: { // 操作
      //       change: (value) => {
      //         console.log(value)
      //         this.headerCheckbox = value; // 确保状态更新
      //         if (value) {
      //           this.selectedRows = [...this.tableData];
      //       }
      //          this.$refs.multipleTableRef.toggleAllSelection(value);
      //           }
      //     },
          
      //   }, column.label)
      // ])
      }
    }
        // 其他列直接返回默认 label
        return column.label
   
    },

    handleSelectAll(val){
      console.log('选择中',val)
      this.headerCheckbox = true
      this.$emit('SelectAll', val)
    },
      handleSelectionChange(val) {
      this.$emit('batchDeleted', val)
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 只合并传进来的列
      // for (let index = 0; index < this.spanArr.length; index++) {
      //   const element = this.spanArr[index];
      //   console.log('element', element)
      //   const a = this.rowSpan(row, column, rowIndex, columnIndex,element.spanColumnIndex,element.spanName)
      //   return a
      // }
      if (this.spanFunc) {
        return this.spanFunc(row, column, rowIndex, columnIndex, this.tableData)
      } else {
        if (this.tableTitle[columnIndex - 1] && this.spanArr.some(p => p.spanName == this.tableTitle[columnIndex - 1].value))
          return this.rowSpan(row, column, rowIndex, columnIndex, columnIndex, this.tableTitle[columnIndex - 1].value)
      }
    },
    rowSpan(row, column, rowIndex, columnIndex, spanColumnIndex, spanName) {
      if (columnIndex === spanColumnIndex) { // 只对第一列（日期列）进行合并
        const date = this.tableData[rowIndex][spanName];
        let span = 1;
        // 如果是第一个数据，或者当前行的日期与前一行不同，则重新计算合并数
        if (
          rowIndex === 0 ||
          this.tableData[rowIndex - 1][spanName] !== date
        ) {
          for (let i = rowIndex + 1; i < this.tableData.length; i++) {
            if (this.tableData[i][spanName] === date) {
              span++;
            } else {
              break;
            }
          }
        } else {
          // 如果不是第一组相同数据的行，则隐藏该单元格
          span = 0;
        }
        // console.log('span',span,date);
        return [span, 1]; // 合并行，列不合并

      }

    },

    updateListQuery(val) {
      this.listQuery = { ...this.listQuery, ...val }
    },
    getQuery(params, row) {
      const p = {}
      for (const i in params) {
        p[i] = row[params[i]]
      }
      return p
    },
    rowClassName({ row, rowIndex }) {
      row.index = rowIndex
      row.xh = rowIndex + 1
    },
    getPageList(v) {
      this.headerCheckbox = false, // 重置状态，让下一页可以选
      this.loading = true
      if (v === 'next') {
        this.dataSource()(this.listQuery).then(res => {
          this.loading = false
          if (res.code === 200) {
            if (this.modelType === 'allReport') {
              this.tableData = [res.data]
              this.total = 0
            } else {
              this.tableData = res.data.pageList
              this.total = res.data.count
              this.$emit('nextEmit', true)

            }
            // 关闭重载
            this.$emit('closeReload', false)
          }
        })
      } else {
        this.dataSource()(this.listQuery).then(res => {
          this.loading = false
          if (res.code === 200) {
            if (this.modelType === 'allReport') {
              this.tableData = [res.data]
              this.total = 0
            } else {
              this.tableData = res.data.pageList
              this.total = res.data.count
            }
            // 关闭重载
            this.$emit('closeReload', false)
          }
        })
      }
    },
    searchFormEmit(v) {
      v.page = 1
      this.updateListQuery(v)
    },
    watchTypeEmit(v) {
      this.$emit('watchTypeEmit2', v)
    },
    refreshForm(v) {
      this.$emit('refreshForm2', v)
    },
  
    refresh() {
      this.$emit('refresh')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table {

  // 每行鼠标经过的样式
  .el-table__body tr:hover>td {
    background-color: rgba($color: #FAFBFD, $alpha: .9) !important;
  }

  .el-table__body tr.current-row>td {
    background-color: rgba($color: #FAFBFD, $alpha: .9) !important;
  }
}
</style>
